/*
 * Set Matrix Zeroes
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

Follow up:
Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
 */
package com.xinpan.exercise;

import java.util.HashSet;
import java.util.Set;

public class SetMatrixZero {
    public void setZeroes(int[][] matrix) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int h = matrix.length;
        int w = matrix[0].length;
        
        Set<Integer> pos = new HashSet<Integer>();
        for(int i = 0; i < h; i++)
        {
            for(int j = 0; j < w; j++)
            {
                if(matrix[i][j] == 0)
                {
                    if(!pos.contains(i*w+j))
                        pos.add(i*w+j);
                }
            }
        }
        for(Integer p : pos)
        {
            int r = p / w;
            int c = p % w;
            for(int i = 0; i < w; i++)
                matrix[r][i] = 0;
            for(int i = 0; i < h; i++)
                matrix[i][c] = 0;
        }
    }
}
